const router = require('koa-router')()

router.prefix('/district')

router.get('/', async(ctx, next) => {
    let selectSql = "select * from classinfor";
    let countSql = "select count(*) as total from classinfor";
    let districtList = await ctx.db.EXECUTE(selectSql);
    let countResult = await ctx.db.EXECUTE(countSql);

    if(districtList.length > 0) {
        ctx.body = {
            status: 'ok',
            districtList: districtList,
            total: countResult.total
        }
    }
})
router.get('/list', async(ctx, next) => {
    let selectSql = "select studentClass from classinfor order by studentClass ASC";
    let districtList = await ctx.db.EXECUTE(selectSql);

    if(districtList.length > 0) {
        ctx.body = {
            status: 'ok',
            districtList: districtList
        }
    }
})


router.post('/add', async(ctx, next) => {
    let addSql = "insert into districts (districtName, organizationId) values (?, ?)";
    let { districtName, organizationId } = ctx.request.body;

    let selectSql = "select * from districts where districtName=? and organizationId=?";
    let selectResult = await ctx.db.EXECUTE(selectSql, districtName, organizationId);

    if(selectResult.length > 0 ) {
        ctx.body = {
            status: 'invalid'
        }
    }
    else {
        let addResult = await ctx.db.EXECUTE(addSql, districtName, organizationId);
        if(addResult.affectedRows > 0) {
            ctx.body = {
                status: 'ok'
            }
        }
    }
})


router.post('/update', async(ctx, next) => {
    let { districtName, organizationId, districtId } = ctx.request.body;
    let selectSql = "select * from districts where districtName=? and organizationId=?";
    let selectResult = await ctx.db.EXECUTE(selectSql, districtName, organizationId);
    if(selectResult.length > 0) {
        ctx.body = {
            status: 'invalid'
        }
    }
    else {
        let updateSql = "update districts set districtName=?, organizationId=? where districtId=?";
        let result = await ctx.db.EXECUTE(updateSql, districtName, organizationId, districtId);
        if(result.affectedRows > 0) {
            ctx.body = {
                status: 'ok'
            }
        }
    }
})


router.post('/del', async(ctx, next) => {
    let classId = ctx.request.body.classId;
    let deleteSql = "delete from classinfor where classId=? ";
    let result = await ctx.db.EXECUTE(deleteSql, classId);
    if(result.affectedRows > 0) {
        ctx.body = {
            status: 'ok'
        }
    }
})

module.exports = router;